package com.ctg.itrdc.sysmgr.permission.core.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.ShiroHttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.itrdc.sysmgr.permission.core.utils.CookieUtils;
import com.ctg.itrdc.sysmgr.permission.core.utils.WebUtils;

public class ExtUserFilter extends UserFilter {

	private Logger logger = LoggerFactory.getLogger(ExtUserFilter.class);

	private Boolean debug = false;

	public void setDebug(Boolean debug) {
		this.debug = debug;
	}
	
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		HttpServletRequest req = (HttpServletRequest) request;
		if (debug) {
			return true;
		}

		Subject subject = getSubject(request, response);
		//TODO 目前只要登录即可,不做用户权限认证
		if(subject.isAuthenticated()){
			return true;
		}
		String servletPath = req.getServletPath();
		boolean permitted = subject.isPermitted(servletPath);
		return permitted;
	}

	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

		ShiroHttpServletRequest req = (ShiroHttpServletRequest) request;
		ShiroHttpServletResponse rep = (ShiroHttpServletResponse) response;

		CookieUtils.cleanCookie(rep, CookieUtils.CTG_USER);

		if (WebUtils.isAjax(req)) {
			logger.debug("用户尚未登录，或session超时。请重新登录后再访问。");
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().write("{\"resultCode\":\"403\",\"resultMsg\":\"用户未登录\"}");

		} else {
			saveRequestAndRedirectToLogin(req, rep);
		}
		return false;
	}

}
